import { createI18nForLib } from './useI18n'
import { getCurrentInstance } from 'vue'



// Fallback implementation when used as a standalone library
let currentLocale: LocaleType = 'zh-CN'
let globalI18n: any = null

// Get the i18n instance from Vue app or fallback to global
const getI18nInstance = () => {
  const instance = getCurrentInstance()
  if (instance?.appContext?.app?.config?.globalProperties?.$i18n) {
    return instance.appContext.app.config.globalProperties.$i18n
  }
  return globalI18n
}

// Deep merge function for locale messages
const deepMerge = (target: any, source: any): any => {
  if (!source || typeof source !== 'object') return target
  if (!target || typeof target !== 'object') return source
  
  const result = { ...target }
  
  for (const key in source) {
    if (source.hasOwnProperty(key)) {
      if (
        typeof source[key] === 'object' && 
        source[key] !== null && 
        !Array.isArray(source[key]) &&
        typeof target[key] === 'object' && 
        target[key] !== null && 
        !Array.isArray(target[key])
      ) {
        result[key] = deepMerge(target[key], source[key])
      } else {
        result[key] = source[key]
      }
    }
  }
  
  return result
}

export const useLocale = () => {
  // Initialize i18n if not already initialized
  if (!globalI18n) {
    globalI18n = createI18nForLib(currentLocale)
  }

  /**
   * 切换语言
   * @param locale 语言代码，如 'zh-CN', 'en'
   * @param customMessages 自定义消息对象，可选。如果提供，将与内置消息合并
   */
  const changeLocale = async (locale: LocaleType, customMessages?: any) => {
    try {
      const i18n = getI18nInstance() || globalI18n
      
      if (!i18n || !i18n.global) {
        console.warn('i18n instance not available')
        return
      }

      // 更新当前语言
      currentLocale = locale
      
      // 设置语言
      if (i18n.mode === 'legacy') {
        i18n.global.locale = locale
      } else {
        i18n.global.locale.value = locale
      }
      // 如果有自定义消息，进行合并
      if (customMessages && typeof customMessages === 'object') {
        // 获取当前语言的消息
        const currentMessages = i18n.global.getLocaleMessage(locale) || {}
        
        // 深度合并自定义消息
        const mergedMessages = deepMerge(currentMessages, customMessages)
        
        // 设置合并后的消息
        i18n.global.setLocaleMessage(locale, mergedMessages)
        
        console.log(`Locale changed to ${locale} with custom messages merged`)
      } else {
        console.log(`Locale changed to ${locale}`)
      }
      
      // 设置 HTML lang 属性
      if (typeof document !== 'undefined') {
        document.documentElement.lang = locale
      }
      
    } catch (error) {
      console.error(`Failed to change locale to ${locale}:`, error)
    }
  }

  /**
   * 获取当前语言
   * @returns 当前语言代码
   */
  const getCurrentLocale = (): LocaleType => {
    const i18n = getI18nInstance() || globalI18n
    if (i18n && i18n.global) {
      if (i18n.mode === 'legacy') {
        return i18n.global.locale
      } else {
        return i18n.global.locale.value
      }
    }
    return currentLocale
  }

  /**
   * 获取指定语言的消息
   * @param locale 语言代码，可选，默认为当前语言
   * @returns 语言消息对象
   */
  const getLocaleMessages = (locale?: LocaleType) => {
    const i18n = getI18nInstance() || globalI18n
    const targetLocale = locale || getCurrentLocale()
    debugger
    if (i18n && i18n.global && i18n.global.getLocaleMessage) {
      return i18n.global.getLocaleMessage(targetLocale)
    }
    return {}
  }

  /**
   * 设置指定语言的消息
   * @param locale 语言代码
   * @param messages 消息对象
   * @param merge 是否与现有消息合并，默认为 true
   */
  const setLocaleMessages = (locale: LocaleType, messages: any, merge: boolean = true) => {
    const i18n = getI18nInstance() || globalI18n
    
    if (!i18n || !i18n.global || !i18n.global.setLocaleMessage) {
      console.warn('i18n instance not available for setting messages')
      return
    }

    if (merge) {
      const currentMessages = i18n.global.getLocaleMessage(locale) || {}
      const mergedMessages = deepMerge(currentMessages, messages)
      i18n.global.setLocaleMessage(locale, mergedMessages)
    } else {
      i18n.global.setLocaleMessage(locale, messages)
    }
  }

  /**
   * 获取可用的语言列表
   * @returns 语言代码数组
   */
  const getAvailableLocales = (): LocaleType[] => {
    const i18n = getI18nInstance() || globalI18n
    
    if (i18n && i18n.global && i18n.global.availableLocales) {
      return i18n.global.availableLocales as LocaleType[]
    }
    return ['zh-CN', 'en']
  }

  return {
    changeLocale,
    getCurrentLocale,
    getLocaleMessages,
    setLocaleMessages,
    getAvailableLocales
  }
}
